"use client"
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import { useEffect, useRef, useState } from 'react';
import * as olProj from 'ol/proj';
import LayersControls from '../LayersControls';

/** longitude 经度 */
const centX = 111.783727873893;
/** latitude 维度 */
const centY = 22.8524013961076;

const OpenLayersMap = () => {

  const mapEleRef = useRef(null);

  const [map, setMap] = useState<Map>()

  useEffect(() => {
    let map: Map;
    if (mapEleRef.current) {

      const epsg = 'EPSG:3857'
      const projection = olProj.get(epsg);
      // const projection = olProj.get('EPSG:4326');

      if (projection) {
        const view = new View({
          center: olProj.transform([centX, centY], 'EPSG:4326', epsg),
          // center: [centX, centY],
          projection: projection,
          zoom: 14,
          minZoom: 10,
          maxZoom: 17
        });

        map = new Map({
          target: mapEleRef.current,
          layers: [
            new TileLayer({
              source: new XYZ({
                url: '/tiles/{z}/{x}/{y}.jpg'
              })
            })
          ],
          view,
          controls: []
        });

        setMap(map)
      }
    }
    return () => {
      map.dispose()
    }
  }, [])

  return (
    <article className='h-screen'>
      <section ref={mapEleRef} className='h-full'></section>

      {map &&
        <div className='absolute top-4 left-4'>
          <LayersControls map={map} />
        </div>
      }

    </article>
  )
}

export default OpenLayersMap